package com.playWright.demo;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import java.nio.file.Paths;

public class Screenshot {
    private Playwright playwright;
    private Browser browser;

    public void launch() {
        playwright = Playwright.create();
        browser = playwright.chromium().launch(
                new BrowserType.LaunchOptions().setHeadless(true)
        );
    }

    public void close() {
        if (browser != null) browser.close();
        if (playwright != null) playwright.close();
    }

    // 1️⃣ HTML 字符串 → byte[]
    public byte[] screenshotFromHtmlText(String html) {
        Page page = browser.newPage();
        page.setContent(html);
        byte[] bytes = page.screenshot(
                new Page.ScreenshotOptions().setFullPage(true)
        );
        page.close();
        return bytes;
    }

    // 2️⃣ 本地 HTML 文件 → byte[]
    public byte[] screenshotFromFile(String filePath) {
        Page page = browser.newPage();
        page.navigate(Paths.get(filePath).toUri().toString());
        byte[] bytes = page.screenshot(
                new Page.ScreenshotOptions().setFullPage(true)
        );
        page.close();
        return bytes;
    }

    // 3️⃣ URL → byte[]
    public byte[] screenshotFromUrl(String url) {
        Page page = browser.newPage();
        page.navigate(url);
        byte[] bytes = page.screenshot(
                new Page.ScreenshotOptions().setFullPage(true)
        );
        page.close();
        return bytes;
    }

    // 测试
    public static void main(String[] args) {
        Screenshot tool = new Screenshot();
        tool.launch();
        byte[] img = tool.screenshotFromHtmlText("<html><body><h1>Hello Stream!</h1></body> </html>");
        System.out.println("截图字节长度: " + img.length);
        tool.close();
    }
}
